package org.lc.oauth.extension.handler;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.lc.oauth.dto.ErrorResult;
import org.lc.platform.base.enums.ResultCodeEnum;
import org.lc.platform.base.result.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * 认证失败处理器
 *
 * @author haoxr
 * @since 3.0.0
 */
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        int code = ResultCodeEnum.FAILED.getCode();
        String msg = e.getMessage();
        if (e instanceof OAuth2AuthenticationException) {
            var error = ((OAuth2AuthenticationException) e).getError();
            var message = error.getDescription();
            if (message == null) {
                message = error.getErrorCode();
            }
            var result = new ErrorResult(message);
            code = result.getCode();
            msg = result.getMsg();
        }
        response.getWriter().write(JSONUtil.toJsonStr(Result.error(code, msg)));
    }
}
